package com.liyunc.demo.service.impl;

import com.liyunc.demo.model.entity.GoodsEntity;
import com.liyunc.demo.model.repository.GoodsRepository;
import com.liyunc.demo.service.GoodsService;
import com.liyunc.demo.utils.OrderRecord;
import com.liyunc.demo.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.concurrent.Executor;


@Service
@Transactional
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private CacheServiceImpl cacheService;

    @Autowired
    private GoodsRepository goodsRepository;

    @Qualifier("applicationTaskExecutor")
    @Autowired
    private Executor executor;

    @Autowired
    private OrderCreateThread orderCreateThread;


    @Override
    public List<GoodsEntity> findAll() {
        // TODO Auto-generated method stub
        return cacheService.findAll();
    }


    @Override
    public GoodsEntity findOne(long id) {
        // TODO Auto-generated method stub
        return cacheService.findOne(id);
    }


    @Override
    public Result saveOrder(long goodsId, String userId) {
        //0.从用户的set集合中判断用户是否已经下单
        LinkedHashSet<String> set = cacheService.userOrderRecords;
        String value = userId + "_order_" + goodsId;
        boolean contains = set.contains(value);
        if (contains) {
            //如果正在排队或者未支付的，提示用户你正在排队或者有订单未支付
            return new Result(false, "对不起，您正在排队等待支付，请尽快支付！");
        }
        //1.从redis队列中获取秒杀商品
        goodsId = cacheService.findOne(goodsId).getGoodsId();
        //2.判断商品是否存在，或库存是否<=0
        if (goodsId == 0) {
            //3.商品不存在，或库存<=0,返回失败，提示已售罄
            return new Result(false, "对不起，商品已售罄，请选择其他商品！");
        }
        //4.将用户放入用户集合
        set.add(value);
        //5.创建OrderRecord对象记录用户下单信息：用户id，商品id
        OrderRecord orderRecord = new OrderRecord(goodsId, userId);
        cacheService.orderRecords.add(orderRecord);
        //6.通过线程池启动线程处理OrderRecord中的数据，返回成功
        executor.execute(orderCreateThread);
        return new Result(true, "秒杀成功，请尽快支付！");
    }
}
